/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufg.inf.si.poo.formula1.GUI;

import br.ufg.inf.si.poo.formula1.Circuit.Circuit;
import br.ufg.inf.si.poo.formula1.Interface.InterfaceRegister;
import br.ufg.inf.si.poo.formula1.Library.Library;
import br.ufg.inf.si.poo.formula1.ManagementFiles.ManagementFiles;
import br.ufg.inf.si.poo.formula1.ManagementFiles.ManagementFilesSeason;
import br.ufg.inf.si.poo.formula1.Season.Season;
import br.ufg.inf.si.poo.formula1.Team.Team;
import java.io.File;
import javax.swing.JOptionPane;

/**
 * RegisterSeason
 *
 * Versao 1.0
 *
 * Data 16/02/2013
 *
 * @author Igor
 */
public class RegisterSeason extends javax.swing.JInternalFrame implements InterfaceRegister {
    //Atributos

    private Season season;
    private Boolean emEdicao; //Valida se esta em modo de edicao ou nao
    private String folderSeason = "./Arquivos/Texto/Temporadas/";//Pasta da temporada
    private Boolean novo; //Variavel que verifica se clicou no botao de novo registro

    //Construtores
    /**
     * Creates new form FramePadrao
     */
    public RegisterSeason() {
        initComponents();
        this.novo = false;
        clearFields();
    }

    //Outros Metodos
    private void checkFolderSeason(int year) throws IllegalArgumentException {
        File pasta = new File(this.folderSeason + year);
        if (!pasta.exists()) {
            throw new IllegalArgumentException("Pasta para a temporada de " + year + " não foi encontrada!");
        }
    }

    /**
     * Exibe as equipes vinculadas no JList de equipes vinculadas
     */
    private void teamsLinkedList() {
        String[] teams = new String[13]; //Maximo de 13 equipes por temporada
        //Lista Equipes Vinculadas
        for (int i = 0; i < this.season.getQttTeams(); i++) {
            if (this.season.getTeams()[i] != null) {
                teams[i] = this.season.getTeams()[i].getShortName();
            }
        }
        this.listEquipesVinculadas.setListData(teams);
    }

    /**
     * Exibe os circuitos vinculados no JList de circuitos vinculados
     */
    private void circuitsLinkedList() {
        String[] circuits = new String[20]; //Maximo de 20 circuitos por temporada
        //Lista Circuitos Vinculados
        for (int i = 0; i < this.season.getQttCircuits(); i++) {
            if (this.season.getCircuits()[i] != null) {
                circuits[i] = this.season.getCircuits()[i].getCountry();
            }
        }
        this.listCircuitosVinculadas.setListData(circuits);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panelTitulo = new javax.swing.JPanel();
        labelTitulo = new javax.swing.JLabel();
        panelDadosPrincipais = new javax.swing.JPanel();
        labelAno = new javax.swing.JLabel();
        textAno = new javax.swing.JTextField();
        panelVincularObjetos = new javax.swing.JPanel();
        pageControlVincularObjetos = new javax.swing.JTabbedPane();
        panelEquipes = new javax.swing.JPanel();
        panelEquipesCadastradas = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        listEquipesCadastradas = new javax.swing.JList();
        panelEquipesVinculadas = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        listEquipesVinculadas = new javax.swing.JList();
        buttonDesvincularEquipe = new javax.swing.JButton();
        buttonVincularEquipe = new javax.swing.JButton();
        panelCircuitos = new javax.swing.JPanel();
        panelCircuitoCadastradas = new javax.swing.JPanel();
        jScrollPane4 = new javax.swing.JScrollPane();
        listCircuitosCadastradas = new javax.swing.JList();
        panelCircuitosVinculadas = new javax.swing.JPanel();
        jScrollPane5 = new javax.swing.JScrollPane();
        listCircuitosVinculadas = new javax.swing.JList();
        buttonVincularCircuito = new javax.swing.JButton();
        buttonDesvincularCircuito = new javax.swing.JButton();
        panelTemporadasCadastradas = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        listTemporadas = new javax.swing.JList();
        buttonCarregarTemporada = new javax.swing.JButton();
        labelCampoCodigo = new javax.swing.JLabel();
        panelBotoes = new javax.swing.JPanel();
        buttonSalvar = new javax.swing.JButton();
        buttonLimpar = new javax.swing.JButton();
        labelCamposObrigatorios = new javax.swing.JLabel();
        buttonNovo = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        setTitle("Cadastrar Temporadas");
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        panelTitulo.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        labelTitulo.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        labelTitulo.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        labelTitulo.setText("Tela utilizada para cadastrar e/ou alterar dados da Temporada");

        javax.swing.GroupLayout panelTituloLayout = new javax.swing.GroupLayout(panelTitulo);
        panelTitulo.setLayout(panelTituloLayout);
        panelTituloLayout.setHorizontalGroup(
            panelTituloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelTituloLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(labelTitulo)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        panelTituloLayout.setVerticalGroup(
            panelTituloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelTituloLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(labelTitulo)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        panelDadosPrincipais.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "   Dados Principais   ", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 10), java.awt.Color.black)); // NOI18N

        labelAno.setText("Ano da Temporada: *");

        textAno.setToolTipText("Ano em que acontece a temporada");

        panelVincularObjetos.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 10), java.awt.Color.black)); // NOI18N

        panelEquipesCadastradas.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "   Cadastradas   ", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 10), java.awt.Color.black)); // NOI18N

        listEquipesCadastradas.setToolTipText("Equipes cadastradas");
        jScrollPane2.setViewportView(listEquipesCadastradas);

        javax.swing.GroupLayout panelEquipesCadastradasLayout = new javax.swing.GroupLayout(panelEquipesCadastradas);
        panelEquipesCadastradas.setLayout(panelEquipesCadastradasLayout);
        panelEquipesCadastradasLayout.setHorizontalGroup(
            panelEquipesCadastradasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 203, Short.MAX_VALUE)
        );
        panelEquipesCadastradasLayout.setVerticalGroup(
            panelEquipesCadastradasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 342, Short.MAX_VALUE)
        );

        panelEquipesVinculadas.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "   Vinculadas   ", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 10), java.awt.Color.black)); // NOI18N

        listEquipesVinculadas.setToolTipText("Equipes vinculadas");
        jScrollPane3.setViewportView(listEquipesVinculadas);

        javax.swing.GroupLayout panelEquipesVinculadasLayout = new javax.swing.GroupLayout(panelEquipesVinculadas);
        panelEquipesVinculadas.setLayout(panelEquipesVinculadasLayout);
        panelEquipesVinculadasLayout.setHorizontalGroup(
            panelEquipesVinculadasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 203, Short.MAX_VALUE)
        );
        panelEquipesVinculadasLayout.setVerticalGroup(
            panelEquipesVinculadasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane3)
        );

        buttonDesvincularEquipe.setText("<<");
        buttonDesvincularEquipe.setToolTipText("Desvincular equipe selecionada");
        buttonDesvincularEquipe.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonDesvincularEquipeActionPerformed(evt);
            }
        });

        buttonVincularEquipe.setText(">>");
        buttonVincularEquipe.setToolTipText("Vincular equipe selecionada");
        buttonVincularEquipe.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonVincularEquipeActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout panelEquipesLayout = new javax.swing.GroupLayout(panelEquipes);
        panelEquipes.setLayout(panelEquipesLayout);
        panelEquipesLayout.setHorizontalGroup(
            panelEquipesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelEquipesLayout.createSequentialGroup()
                .addComponent(panelEquipesCadastradas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelEquipesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(buttonVincularEquipe)
                    .addComponent(buttonDesvincularEquipe))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(panelEquipesVinculadas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        panelEquipesLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {panelEquipesCadastradas, panelEquipesVinculadas});

        panelEquipesLayout.setVerticalGroup(
            panelEquipesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panelEquipesCadastradas, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(panelEquipesVinculadas, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(panelEquipesLayout.createSequentialGroup()
                .addGap(108, 108, 108)
                .addComponent(buttonVincularEquipe)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonDesvincularEquipe)
                .addContainerGap())
        );

        pageControlVincularObjetos.addTab("Equipes", panelEquipes);

        panelCircuitoCadastradas.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "   Cadastradas   ", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 10), java.awt.Color.black)); // NOI18N

        listCircuitosCadastradas.setToolTipText("Equipes cadastradas");
        jScrollPane4.setViewportView(listCircuitosCadastradas);

        javax.swing.GroupLayout panelCircuitoCadastradasLayout = new javax.swing.GroupLayout(panelCircuitoCadastradas);
        panelCircuitoCadastradas.setLayout(panelCircuitoCadastradasLayout);
        panelCircuitoCadastradasLayout.setHorizontalGroup(
            panelCircuitoCadastradasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 203, Short.MAX_VALUE)
        );
        panelCircuitoCadastradasLayout.setVerticalGroup(
            panelCircuitoCadastradasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 342, Short.MAX_VALUE)
        );

        panelCircuitosVinculadas.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "   Vinculadas   ", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 10), java.awt.Color.black)); // NOI18N

        listCircuitosVinculadas.setToolTipText("Equipes vinculadas");
        jScrollPane5.setViewportView(listCircuitosVinculadas);

        javax.swing.GroupLayout panelCircuitosVinculadasLayout = new javax.swing.GroupLayout(panelCircuitosVinculadas);
        panelCircuitosVinculadas.setLayout(panelCircuitosVinculadasLayout);
        panelCircuitosVinculadasLayout.setHorizontalGroup(
            panelCircuitosVinculadasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 203, Short.MAX_VALUE)
        );
        panelCircuitosVinculadasLayout.setVerticalGroup(
            panelCircuitosVinculadasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane5)
        );

        buttonVincularCircuito.setText(">>");
        buttonVincularCircuito.setToolTipText("Vincular equipe selecionada");
        buttonVincularCircuito.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonVincularCircuitoActionPerformed(evt);
            }
        });

        buttonDesvincularCircuito.setText("<<");
        buttonDesvincularCircuito.setToolTipText("Desvincular equipe selecionada");
        buttonDesvincularCircuito.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonDesvincularCircuitoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout panelCircuitosLayout = new javax.swing.GroupLayout(panelCircuitos);
        panelCircuitos.setLayout(panelCircuitosLayout);
        panelCircuitosLayout.setHorizontalGroup(
            panelCircuitosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelCircuitosLayout.createSequentialGroup()
                .addComponent(panelCircuitoCadastradas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelCircuitosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(buttonVincularCircuito)
                    .addComponent(buttonDesvincularCircuito))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(panelCircuitosVinculadas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        panelCircuitosLayout.setVerticalGroup(
            panelCircuitosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panelCircuitoCadastradas, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(panelCircuitosVinculadas, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(panelCircuitosLayout.createSequentialGroup()
                .addGap(108, 108, 108)
                .addComponent(buttonVincularCircuito)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonDesvincularCircuito)
                .addContainerGap())
        );

        pageControlVincularObjetos.addTab("Circuitos", panelCircuitos);

        javax.swing.GroupLayout panelVincularObjetosLayout = new javax.swing.GroupLayout(panelVincularObjetos);
        panelVincularObjetos.setLayout(panelVincularObjetosLayout);
        panelVincularObjetosLayout.setHorizontalGroup(
            panelVincularObjetosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pageControlVincularObjetos, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE)
        );
        panelVincularObjetosLayout.setVerticalGroup(
            panelVincularObjetosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pageControlVincularObjetos)
        );

        panelTemporadasCadastradas.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "   Temporadas   ", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 10), java.awt.Color.black)); // NOI18N

        listTemporadas.setToolTipText("Lista de temporada cadastradas");
        listTemporadas.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                listTemporadasValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(listTemporadas);

        buttonCarregarTemporada.setText("Carregar Temporada");
        buttonCarregarTemporada.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonCarregarTemporadaActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout panelTemporadasCadastradasLayout = new javax.swing.GroupLayout(panelTemporadasCadastradas);
        panelTemporadasCadastradas.setLayout(panelTemporadasCadastradasLayout);
        panelTemporadasCadastradasLayout.setHorizontalGroup(
            panelTemporadasCadastradasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE)
            .addComponent(buttonCarregarTemporada, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        panelTemporadasCadastradasLayout.setVerticalGroup(
            panelTemporadasCadastradasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelTemporadasCadastradasLayout.createSequentialGroup()
                .addComponent(jScrollPane1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonCarregarTemporada))
        );

        labelCampoCodigo.setText("Campo código");
        labelCampoCodigo.setToolTipText("Não editar");

        javax.swing.GroupLayout panelDadosPrincipaisLayout = new javax.swing.GroupLayout(panelDadosPrincipais);
        panelDadosPrincipais.setLayout(panelDadosPrincipaisLayout);
        panelDadosPrincipaisLayout.setHorizontalGroup(
            panelDadosPrincipaisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelDadosPrincipaisLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelDadosPrincipaisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panelDadosPrincipaisLayout.createSequentialGroup()
                        .addComponent(labelAno)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(textAno, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(labelCampoCodigo))
                    .addComponent(panelVincularObjetos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(panelTemporadasCadastradas, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        panelDadosPrincipaisLayout.setVerticalGroup(
            panelDadosPrincipaisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelDadosPrincipaisLayout.createSequentialGroup()
                .addGroup(panelDadosPrincipaisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(labelAno)
                    .addComponent(textAno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelCampoCodigo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(panelVincularObjetos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addComponent(panelTemporadasCadastradas, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        panelBotoes.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        buttonSalvar.setText("Salvar");
        buttonSalvar.setToolTipText("Clique para salvar os dados digitados");
        buttonSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSalvarActionPerformed(evt);
            }
        });

        buttonLimpar.setText("Limpar");
        buttonLimpar.setToolTipText("Clique para limpar a tela e habilitar um novo registro");
        buttonLimpar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonLimparActionPerformed(evt);
            }
        });

        labelCamposObrigatorios.setText("Campos marcados com *, são obrigatórios");

        buttonNovo.setText("Novo");
        buttonNovo.setToolTipText("Clique para cadastrar um novo registro");
        buttonNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonNovoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout panelBotoesLayout = new javax.swing.GroupLayout(panelBotoes);
        panelBotoes.setLayout(panelBotoesLayout);
        panelBotoesLayout.setHorizontalGroup(
            panelBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelBotoesLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(labelCamposObrigatorios)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(buttonNovo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonSalvar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonLimpar)
                .addContainerGap())
        );

        panelBotoesLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {buttonLimpar, buttonNovo, buttonSalvar});

        panelBotoesLayout.setVerticalGroup(
            panelBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelBotoesLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(buttonNovo)
                    .addComponent(buttonSalvar)
                    .addComponent(buttonLimpar)
                    .addComponent(labelCamposObrigatorios))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(panelDadosPrincipais, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(panelTitulo, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(panelBotoes, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panelTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(panelDadosPrincipais, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(panelBotoes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void buttonLimparActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonLimparActionPerformed
        clearFields();
    }//GEN-LAST:event_buttonLimparActionPerformed

    /**
     * Evento do Frame, sempre que e adicionado ao DesktopPane
     *
     * @param evt
     */
    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        clearFields();
    }//GEN-LAST:event_formComponentShown

    private void buttonVincularEquipeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonVincularEquipeActionPerformed
        //Verifica se existe algum item selecionado
        if (this.season != null) {
            if (!this.season.validateSeasonStarted()) {
                if (this.listEquipesCadastradas.getSelectedIndex() != -1) {
                    Team team = Library.returnTeam((String) this.listEquipesCadastradas.getSelectedValue());
                    if (team != null) {
                        this.season.setTeams(team);
                    }
                }
            } else {
                JOptionPane.showMessageDialog(this, "Impossível vincular/desvincular! A Temporada já começou.", "Atenção!", JOptionPane.INFORMATION_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(this, "Selecione uma Temporada!", "Atenção!", JOptionPane.INFORMATION_MESSAGE);
        }
        teamsLinkedList();
    }//GEN-LAST:event_buttonVincularEquipeActionPerformed

    private void buttonSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSalvarActionPerformed
        try {
            checkFields();

            checkValueEntered();

            createObject();

            clearFields();
        } catch (IllegalArgumentException e) {
            JOptionPane.showMessageDialog(this, e.getMessage(), "Erro!", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_buttonSalvarActionPerformed

    private void buttonDesvincularEquipeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonDesvincularEquipeActionPerformed
        // TODO add your handling code here:
        if (this.season != null) {
            if (!this.season.validateSeasonStarted()) {
                if (this.listEquipesVinculadas.getSelectedIndex() != -1) {
                    Team team = Library.returnTeam((String) this.listEquipesVinculadas.getSelectedValue());
                    if (team != null) {
                        this.season.removeTeamSeason(team);
                    }
                } else {
                    JOptionPane.showMessageDialog(this, "Selecione uma Equipe!", "Atenção!", JOptionPane.INFORMATION_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(this, "Impossível vincular/desvincular! A Temporada já começou.", "Atenção!", JOptionPane.INFORMATION_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(this, "Selecione uma Temporada!", "Atenção!", JOptionPane.INFORMATION_MESSAGE);
        }

        teamsLinkedList();
    }//GEN-LAST:event_buttonDesvincularEquipeActionPerformed

    private void buttonVincularCircuitoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonVincularCircuitoActionPerformed
        // TODO add your handling code here:
        if (this.season != null) {
            if (!this.season.validateSeasonStarted()) {
                if (this.listCircuitosCadastradas.getSelectedIndex() != -1) {
                    Circuit circuit = Library.returnCircuit((String) this.listCircuitosCadastradas.getSelectedValue());
                    if (circuit != null) {
                        this.season.setCircuits(circuit);
                    }
                }
            } else {
                JOptionPane.showMessageDialog(this, "Impossível vincular/desvincular! A Temporada já começou.", "Atenção!", JOptionPane.INFORMATION_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(this, "Selecione uma Temporada!", "Atenção!", JOptionPane.INFORMATION_MESSAGE);
        }
        circuitsLinkedList();
    }//GEN-LAST:event_buttonVincularCircuitoActionPerformed

    private void buttonDesvincularCircuitoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonDesvincularCircuitoActionPerformed
        // TODO add your handling code here:
        if (this.season != null) {
            if (!this.season.validateSeasonStarted()) {
                if (this.listCircuitosVinculadas.getSelectedIndex() != -1) {
                    Circuit circuit = Library.returnCircuit((String) this.listCircuitosVinculadas.getSelectedValue());
                    if (circuit != null) {
                        this.season.removeCircuitSeason(circuit);
                    }
                } else {
                    JOptionPane.showMessageDialog(this, "Selecione um Circuito!", "Atenção!", JOptionPane.INFORMATION_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(this, "Impossível vincular/desvincular! A Temporada já começou.", "Atenção!", JOptionPane.INFORMATION_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(this, "Selecione uma Temporada!", "Atenção!", JOptionPane.INFORMATION_MESSAGE);
        }
        circuitsLinkedList();
    }//GEN-LAST:event_buttonDesvincularCircuitoActionPerformed

    private void buttonNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonNovoActionPerformed
        // TODO add your handling code here:
        this.novo = true; //Diz para o clearFields() que sera um novo registro
        clearFields();
    }//GEN-LAST:event_buttonNovoActionPerformed

    private void buttonCarregarTemporadaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCarregarTemporadaActionPerformed
        // TODO add your handling code here:
        try {
            checkFolderSeason(this.season.getYear());

            ManagementFilesSeason.resetDataSeason();
            FrameMain.setSeasonLoaded(this.season);

            ManagementFilesSeason.readHireDriverSeason(FrameMain.getSeasonLoaded(), FrameMain.getFolderSeasonLoaded());
            ManagementFilesSeason.readCircuitSeason(FrameMain.getSeasonLoaded(), FrameMain.getFolderSeasonLoaded());
            ManagementFilesSeason.readRaceSeason(FrameMain.getSeasonLoaded(), FrameMain.getFolderSeasonLoaded());
            ManagementFilesSeason.createRaceSeason(FrameMain.getSeasonLoaded()); //Crias as corridas que por algum motivo nao foram salvas o.0
            ManagementFilesSeason.readWorldChampionshipDrivers(FrameMain.getSeasonLoaded(), FrameMain.getFolderSeasonLoaded());
            ManagementFilesSeason.readWorldChampionshipBuilders(FrameMain.getSeasonLoaded(), FrameMain.getFolderSeasonLoaded());

            JOptionPane.showMessageDialog(this, "Temporada de " + this.season.getYear() + " carregada com sucesso!", "Atenção!", JOptionPane.INFORMATION_MESSAGE);

            if(!this.season.validateSeasonStarted()){
                JOptionPane.showMessageDialog(this, "Antes de iniciar a Temporada (simulando corridas), tenha certeza\n"+
                                                    "de que a configurou corretamente, pois não será possível altera-lá\n"+
                                                    "após seu início."
                                                    , "Atenção!", JOptionPane.WARNING_MESSAGE);
            }
        } catch (IllegalArgumentException e) {
            JOptionPane.showMessageDialog(this, e.getMessage(), "Erro!", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_buttonCarregarTemporadaActionPerformed

    private void listTemporadasValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_listTemporadasValueChanged
        // TODO add your handling code here:
        if (this.listTemporadas.getSelectedIndex() != -1) {
            Season season1 = Library.returnSeason(Integer.parseInt((String) this.listTemporadas.getSelectedValue()));
            if (season1 != null) {
                this.season = season1;
                this.emEdicao = true;
            }
        }
        dataShowObject();
    }//GEN-LAST:event_listTemporadasValueChanged
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonCarregarTemporada;
    private javax.swing.JButton buttonDesvincularCircuito;
    private javax.swing.JButton buttonDesvincularEquipe;
    private javax.swing.JButton buttonLimpar;
    private javax.swing.JButton buttonNovo;
    private javax.swing.JButton buttonSalvar;
    private javax.swing.JButton buttonVincularCircuito;
    private javax.swing.JButton buttonVincularEquipe;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JLabel labelAno;
    private javax.swing.JLabel labelCampoCodigo;
    private javax.swing.JLabel labelCamposObrigatorios;
    private javax.swing.JLabel labelTitulo;
    private javax.swing.JList listCircuitosCadastradas;
    private javax.swing.JList listCircuitosVinculadas;
    private javax.swing.JList listEquipesCadastradas;
    private javax.swing.JList listEquipesVinculadas;
    private javax.swing.JList listTemporadas;
    private javax.swing.JTabbedPane pageControlVincularObjetos;
    private javax.swing.JPanel panelBotoes;
    private javax.swing.JPanel panelCircuitoCadastradas;
    private javax.swing.JPanel panelCircuitos;
    private javax.swing.JPanel panelCircuitosVinculadas;
    private javax.swing.JPanel panelDadosPrincipais;
    private javax.swing.JPanel panelEquipes;
    private javax.swing.JPanel panelEquipesCadastradas;
    private javax.swing.JPanel panelEquipesVinculadas;
    private javax.swing.JPanel panelTemporadasCadastradas;
    private javax.swing.JPanel panelTitulo;
    private javax.swing.JPanel panelVincularObjetos;
    private javax.swing.JTextField textAno;
    // End of variables declaration//GEN-END:variables

    //Metodos reescritos da interface InterfaceRegister
    @Override
    public void dataShowObject() {
        this.textAno.setText("" + this.season.getYear());

        Library.indexedListTeams(this.listEquipesCadastradas, FrameMain.getTeams(), null);
        Library.indexedListCircuits(this.listCircuitosCadastradas, FrameMain.getCircuits(), null);
        teamsLinkedList();
        circuitsLinkedList();
        Library.indexedListSeason(this.listTemporadas, FrameMain.getSeasons());
    }

    @Override
    public void checkFields() throws IllegalArgumentException {
        if (this.textAno.getText().equals("")) {
            throw new IllegalArgumentException("Campos obrigatórios estão vazios.");
        }
    }

    @Override
    public void checkValueEntered() throws IllegalArgumentException {
        try {
            Integer.parseInt(this.textAno.getText());
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Valor inválido digitado para Ano da Temporada!");
        }
    }

    @Override
    public void createObject() throws IllegalArgumentException {
        int ano = Integer.parseInt(this.textAno.getText());

        //Se nao estiver em modo de edicao entao adiciona, pois eh um novo Objeto, caso contrario apenas alterara
        if (!this.emEdicao) {
            if (Library.returnSeason(ano) != null) {
                throw new IllegalArgumentException("Temporada com Ano de " + this.textAno.getText() + " já cadastrada.");
            }
            File dir = new File(this.folderSeason + ano);
            dir.mkdirs();
            this.season.setYear(ano);
            FrameMain.setSeasons(this.season);
        }
        ManagementFiles.writeSeason(FrameMain.getSeasons());
    }

    @Override
    public void clearFields() {
        this.season = new Season();
        this.emEdicao = false;

        if(!this.novo){
            this.listTemporadas.setSelectedIndex(0);
        }
        this.novo = false;

        dataShowObject();
        Library.indexedListTeams(this.listEquipesCadastradas, FrameMain.getTeams(), null);
        Library.indexedListCircuits(this.listCircuitosCadastradas, FrameMain.getCircuits(), null);
    }
}
